package com.tuliyou.interceptor;

import com.tuliyou.common.util.JwtUtil;
import com.tuliyou.common.util.UserHolder;
import com.tuliyou.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果是登录或者注册操作，直接放行了
        // 获取请求头中token，即JWT令牌
        String jwt = request.getHeader("Authorization");
        // 检查JWT令牌是否存在
        if (jwt == null || !jwt.startsWith("Bearer ")) {
            log.info("令牌不存在！登陆失败！");
            return false;
        }
        String token = jwt.replace("Bearer ", "");
        // 检查JWT令牌是否过期
        if(JwtUtil.isTokenExpired(token)){
            log.info("JWT令牌已过期");
            return false;
        }
        // 解析JWT令牌里的用户id，username和userType并存放在user里
        Long userId = JwtUtil.getUserId(token);
        String username = JwtUtil.getUsername(token);
        String userType = JwtUtil.getUserType(token);
        User user = new User();
        user.setId(userId);
        user.setUsername(username);
        user.setUserType(userType);
        // 解析JWT令牌
        if(!JwtUtil.validateToken(token, userId, username, userType)){
            // 解析失败，捕获失败结果，记录错误日志
            log.info("JWT令牌解析失败");
            return false;
        }
        // 解析成功，把user存入UserHolder
        UserHolder.saveUser(user);
        // 放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserHolder.removeUser();
    }
}
